<?php
/** @var \MageSuite\Magepack\Block\BundlesLoader $block */

$commonBundleUrl = $block->getCommonBundleUrl();
$pageBundlesUrls = $block->getPageBundlesUrls();
//$commonBundleUrl1=$block->getCommonBundleUrl1();

$prefetchBundlesUrls = $block->getPrefetchBundlesUrls();

?>

<?php if (!empty($commonBundleUrl)): ?>
<?php foreach ($commonBundleUrl as $item): ?>
<link rel="prefetch" as="script" href="<?= $item; ?>"/>
<?php endforeach; ?>
<?php endif; ?>

<?php foreach($pageBundlesUrls as $pageBundleUrl): ?>
<link rel="prefetch" as="script" href="<?= $pageBundleUrl; ?>"/>
<?php endforeach; ?>

<?php if (!empty($prefetchBundlesUrls)): ?>
<script>
(function(root, doc) {
    var headElement,
        bundleLink,
        bundleUrls = <?= json_encode($prefetchBundlesUrls); ?>,
        idleCallback = root.requestIdleCallback || root.setTimeout;
    // Prefetch all bundles via link tags when browser gets idle.
    if (headElement = doc.querySelector('head')) {
        root.addEventListener('load', function() {
            idleCallback(function() {
                bundleUrls.forEach(function(bundleUrl) {
                    bundleLink = doc.createElement('link');
                    bundleLink.rel = 'prefetch';
                    bundleLink.as = 'script';
                    bundleLink.href = bundleUrl;
                    headElement.appendChild(bundleLink);
                });
            });
        });
    }
}(window, document))
</script>
<?php endif; ?>
